package com.hrbxlh.action;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hrbxlh.util.ConfigFileUtil;
import com.hrbxlh.util.ImageTools;
import com.hrbxlh.util.PubMethods;
import com.hrbxlh.util.SessionValues;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.CourseActionImpl;
import com.hrbxlh.actionImpl.DepartMentActionImpl;
import com.hrbxlh.actionImpl.SiteActionImpl;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：SiteAction.java
* Description：上课地点action类
* History：
* Date           Author               Desc
* 2017.04.11	  xzx                  建立	
* -------------------------------------------------------
*/
@Controller
public class SiteAction {
	
	@Autowired
	@Qualifier("siteActionImpl")
	private SiteActionImpl siteActionImpl;
	
	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;
	
	@Autowired
	@Qualifier("departMentActionImpl")
	private DepartMentActionImpl departMentActionImpl;
	
	/**xzx
	 * @description 地点管理列表
	 * @param request
	 * @param response
	 * @return  跳转到地点管理列表页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipSiteMana", method = RequestMethod.POST)
	public void skipSiteMana(String jsonStr, HttpServletResponse response)   {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		try {
			Map<String,Object> preParamMap = new HashMap<String, Object>();
			//获取参数值
			if(jsonStr != null){
				preParamMap = mapper.readValue(jsonStr, resultMap.getClass());
			}
			if(courseActionImpl.getMapSpecialMark(response, mapper, resultMap, preParamMap)) return;
			//获取地点列表
			Map<String, Object> siteMap = siteActionImpl.getSiteList(preParamMap);
			if(siteMap != null){
				resultMap.put("siteList", siteMap.get("siteList"));
				resultMap.put("totalPage", siteMap.get("totalPage"));
				resultMap.put("pageNow", siteMap.get("pageNow"));
			}
			//返回条件
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			resultMap.put("siteName", preParamMap.get("siteName"));
			//全部院系
			List<Map<String, Object>> departmentList = departMentActionImpl.getDepartmentAll(new HashMap<String, Object>());
			resultMap.put("departmentList", departmentList);
			resultMap.put("departmentId", preParamMap.get("departmentId"));
			resultMap.put("result", "success");
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap) );
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("跳地点管理页面出现异常skipSiteMana", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap) );
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}
	

	
	/**xzx
	 * @dscription 添加地点
	 * @param response
	 * @return  地点名称
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addSite", method = RequestMethod.POST)
	public void  addSite (HttpServletResponse response, String jsonStr)   {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		try { 
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			if(courseActionImpl.getMapSpecialMark(response, mapper, resultMap, paramMap)) return;
			//添加地点信息
			Map<String, Object> addResultMap = siteActionImpl.addSite(paramMap);
			Boolean flag = (Boolean)addResultMap.get("result");
			//返回参数
			resultMark = (flag) ? "success" : "fail";
			resultMap.put("result", resultMark);
			if(resultMark.equals("fail")){
				resultMap.put("failMsg", addResultMap.get("failMsg"));
			}
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("添加地点出现异常addSite", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**xzx
	 * @description 进入修改地点页面
	 * @param request
	 * @param response
	 * @return  跳转到修改地点页面
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipSaveSite", method = RequestMethod.POST)
	public void skipSaveSite(String jsonStr, HttpServletResponse response)   {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			Map<String,Object> siteDetail = siteActionImpl.getSiteDetail(paramMap);
			resultMap.put("siteDetail", siteDetail);
			resultMap.put("result", "success");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("跳修改地点页面出现异常skipSaveSite", e);
		} finally {
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**xzx
	 * @description 修改地点
	 * @param response
	 * @return  地点名称
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/saveSite", method = RequestMethod.POST)
	public void  saveSite (HttpServletResponse response, String jsonStr)   {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		try { 
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			if(courseActionImpl.getMapSpecialMark(response, mapper, resultMap, paramMap)) return;
			//修改地点信息
			Map<String, Object> saveResultMap = siteActionImpl.saveSite(paramMap);
			Boolean flag = (Boolean)saveResultMap.get("result");
			//返回参数
			resultMark = (flag) ? "success" : "fail";
			resultMap.put("result", resultMark);
			if(resultMark.equals("fail")){
				resultMap.put("failMsg", saveResultMap.get("failMsg"));
			}
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("修改地点出现异常saveSite", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**xzx
	 * @description 删除地点
	 * @param response
	  //jsonStr = ["1","2","3"]
	 * @return  地点id
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delSites", method = RequestMethod.POST)
	public void  delSites (HttpServletResponse response, String jsonStr)   {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		List<String> list = new ArrayList<String>();
		try {
			//获取参数值
			list = mapper.readValue(jsonStr, list.getClass());
			//删除院系信息
			Map<String, Object> result = siteActionImpl.delSites(list);
			boolean resultMarkUse = (Boolean)result.get("result");
			//返回参数
			resultMark = (resultMarkUse) ? "success" : "fail";
			resultMap.put("result", resultMark);
			if(!resultMarkUse){
				resultMap.put("failMsg",result.get("failMsg"));
			}
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("删除地点出现异常delSites", e);
		} finally {
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 商莹
	 * @param request
	 * @param response
	 * @return  上传or修改图标
	 * @throws IOException
	 */
	@RequestMapping(value = "/addSchoolIcon", method = RequestMethod.POST)
	public void addSchoolIcon(
			@RequestParam(value = "file") MultipartFile file,int schIconId,
			HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();

		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String fileName = "";
		//获取当前登陆人的id
		Map<String, Object> sessionMap = new SessionValues().getSessionValues(new String[] {"stuorteaId"}, request, "userMsg");
		String stuorteaId = String.valueOf(sessionMap.get("stuorteaId"));
		if(file!=null){
			fileName = file.getOriginalFilename();
		}
		logger.info("上传图标的参数file为："+fileName);

		String view = "";
		String reJsonStr = "";
		try {
			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String fileName1 = "";
			// 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
			String ext = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
			// 对扩展名进行小写转换
			ext = ext.toLowerCase();
			if(!ext.equals("")&&ext!=null){
				if(!ext.equals("png")&&!ext.equals("jpg")&&!ext.equals("jpeg")){
					resultMap.put("result","fail");
					resultMap.put("failMsg","图片格式不正确");
					return;
				}
			}
			/*if (ext.equals("png")&&!ext.equals("")&&ext!=null) {
				fileName1 = stuorteaId +fileName+ "." + ext;
			} if(!ext.equals("png")&&!ext.equals("")&&ext!=null) {
				fileName1 = stuorteaId +fileName+ ".png";
			}*/
			fileName1 = stuorteaId +fileName;
			if (fileName != "") {
				//判断文件夹存不存在,不存在就创建
				String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/images"+"/"+fileName1;
				File saveFile = new File(path);
				if (!saveFile.exists()) {
					String s = path.substring(0,path.lastIndexOf("/") + 1);
					File saveFileDir = new File(s);
					saveFileDir.mkdirs();
				}
				File destFile = new File(path);//获取图片的高和宽
				double height = ImageTools.getOnlineImgHeight(file);
				double width = ImageTools.getOnlineImgWidth(file);
				map.put("schoolIcon", fileName1);
				FileUtils.copyInputStreamToFile(file.getInputStream(),destFile);// 复制临时文件到指定目录下
				//判断当前图片的高和宽是否符合要求并且进行压缩
				PubMethods.compressImage(width,height,destFile);
			} else {
				map.put("schoolIcon", "");
			}
			map.put("schIconId",schIconId);
			// 往数据库里面插入
			Map<String,Object> memMap = siteActionImpl.addSchoolIcon(map);
			boolean resultFlag = (Boolean) memMap.get("flag");
			String msg = resultFlag==true?"上传成功":"上传失败";
			String str = resultFlag==true?"success":"fail";
			resultMap.put("result",str);
			resultMap.put("failMsg",msg);
			String schoolIconUrl = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/images"+"/"+String.valueOf(memMap.get("schoolIcon"));
			resultMap.put("schoolIconUrl",schoolIconUrl);
			resultMap.put("schoolIcon",fileName1);
			resultMap.put("updateTime",memMap.get("updateTime"));
			logger.info("上传图标返回的结果"+resultMap);

		} catch (Exception e) {
			resultMap.put("failMsg", "操作失败");
			e.printStackTrace();
			logger.error("上传失败", e);

		} finally {
			logger.info("上传图标返回的结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}

	/**
	 * @description 开启or禁用
	 * @param response mark 0禁用 1开启   schIconId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/saveSchMark", method = RequestMethod.POST)
	public void  saveSchMark (HttpServletResponse response, String jsonStr)   {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			if(courseActionImpl.getMapSpecialMark(response, mapper, resultMap, paramMap)) return;
			//开启or禁用
			Map<String, Object> saveResultMap = siteActionImpl.saveSchMark(paramMap);
			Boolean flag = (Boolean)saveResultMap.get("result");
			//返回参数
			resultMark = (flag) ? "success" : "fail";
			resultMap.put("result", resultMark);
			resultMap.put("failMsg", saveResultMap.get("failMsg"));
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("开启or禁用出现异常saveSite", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}

	/***
	 * @description 获取图标信息
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getSchIconInfo", method = RequestMethod.POST)
	public void getSchIconInfo( HttpServletResponse response)   {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		try {
			//获取参数值
//			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			Map<String,Object> schIconDetail = siteActionImpl.getSchIconInfo();
			resultMap.put("schIconDetail", schIconDetail);
			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String schoolIconUrl = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/images";
			resultMap.put("schoolIconUrl",schoolIconUrl);
			resultMap.put("result", "success");
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("获取图标信息出现异常getSchIconInfo", e);
		} finally {
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}
}